package edu.yzu.testspringboot002.config.wechat;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaRedissonConfigImpl;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxRuntimeException;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(WxMaProperties.class)
public class WxMaConfiguration {
    private final WxMaProperties properties;

    /**
     * wx配置
     *
     * @param properties 属性
     */
    @Autowired
    public WxMaConfiguration(WxMaProperties properties) {
        this.properties = properties;
    }

    @Autowired
    private RedissonClient redissonClient;

    /**
     * wx服务
     *
     * @return {@link WxMaService}
     */
    @Bean
    public WxMaService wxMaService() {
        List<WxMaProperties.Config> configs = this.properties.getConfigs();
        if (configs == null) {
            throw new WxRuntimeException("小程序配置信息不合法！");
        }
        WxMaService maService = new WxMaServiceImpl();
        maService.setMultiConfigs(
                configs.stream()
                        .map(item -> {
                            WxMaRedissonConfigImpl config = new WxMaRedissonConfigImpl(redissonClient);
                            // 使用上面的配置时，需要同时引入jedis-lock的依赖，否则会报类无法找到的异常
                            config.setAppid(item.getAppid());
                            config.setSecret(item.getSecret());
                            config.setToken(item.getToken());
                            config.setAesKey(item.getAesKey());
                            config.setMsgDataFormat(item.getMsgDataFormat());
                            return config;
                        }).collect(Collectors.toMap(WxMaDefaultConfigImpl::getAppid, a -> a, (o, n) -> o)));

        return maService;
    }

//    @Bean
//    public WxMaMessageRouter wxMaMessageRouter(WxMaService wxMaService) {
//        final WxMaMessageRouter router = new WxMaMessageRouter(wxMaService);
//        router
//                .rule().handler(logHandler).next()
//                .rule().async(false).content("订阅消息").handler(subscribeMsgHandler).end()
//                .rule().async(false).content("文本").handler(textHandler).end()
//                .rule().async(false).content("图片").handler(picHandler).end()
//                .rule().async(false).content("二维码").handler(qrcodeHandler).end();
//        return router;
//    }
//
//    private final WxMaMessageHandler subscribeMsgHandler = (wxMessage, context, service, sessionManager) -> {
//        service.getMsgService().sendSubscribeMsg(WxMaSubscribeMessage.builder()
//                .templateId("")
//                .data(Lists.newArrayList(
//                        new WxMaSubscribeMessage.MsgData("keyword1", "339208499")))
//                .toUser(wxMessage.getFromUser())
//                .build());
//        return null;
//    };
//
//    private final WxMaMessageHandler logHandler = (wxMessage, context, service, sessionManager) -> {
//        log.info("收到消息：" + wxMessage.toString());
//        service.getMsgService().sendKefuMsg(WxMaKefuMessage.newTextBuilder().content("收到信息为：" + wxMessage.toJson())
//                .toUser(wxMessage.getFromUser()).build());
//        return null;
//    };
//
//    private final WxMaMessageHandler textHandler = (wxMessage, context, service, sessionManager) -> {
//        service.getMsgService().sendKefuMsg(WxMaKefuMessage.newTextBuilder().content("回复文本消息")
//                .toUser(wxMessage.getFromUser()).build());
//        return null;
//    };
//
//    private final WxMaMessageHandler picHandler = (wxMessage, context, service, sessionManager) -> {
//        try {
//            WxMediaUploadResult uploadResult = service.getMediaService()
//                    .uploadMedia("image", "png",
//                            ClassLoader.getSystemResourceAsStream("tmp.png"));
//            service.getMsgService().sendKefuMsg(
//                    WxMaKefuMessage
//                            .newImageBuilder()
//                            .mediaId(uploadResult.getMediaId())
//                            .toUser(wxMessage.getFromUser())
//                            .build());
//        } catch (WxErrorException e) {
//            e.printStackTrace();
//        }
//
//        return null;
//    };
//
//    private final WxMaMessageHandler qrcodeHandler = (wxMessage, context, service, sessionManager) -> {
//        try {
//            final File file = service.getQrcodeService().createQrcode("123", 430);
//            WxMediaUploadResult uploadResult = service.getMediaService().uploadMedia("image", file);
//            service.getMsgService().sendKefuMsg(
//                    WxMaKefuMessage
//                            .newImageBuilder()
//                            .mediaId(uploadResult.getMediaId())
//                            .toUser(wxMessage.getFromUser())
//                            .build());
//        } catch (WxErrorException e) {
//            e.printStackTrace();
//        }
//
//        return null;
//    };

}